package com.ltsh.fim.server;

import com.alibaba.fastjson.JSONObject;
import com.ltsh.fim.common.impl.MyDecoderImpl;
import com.ltsh.fim.common.impl.MyEncoderImpl;
import com.ltsh.fim.common.inf.MyDecoder;
import com.ltsh.fim.common.inf.MyEncoder;
import com.ltsh.fim.common.model.FimRequest;
import com.ltsh.fim.server.config.ServiceContext;
import com.ltsh.fim.server.impl.DefaultSection;
import com.ltsh.fim.server.inf.Section;
import com.ltsh.fim.server.inf.ServerHandler;
import com.ltsh.fim.server.model.resp.ResultResp;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.internal.ThreadLocalRandom;

import java.io.UnsupportedEncodingException;

/**
 * Created by root on 1/11/18.
 */
public class ChineseProverbServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    public ChineseProverbServerHandler(Section section) {
        this.section = section;
    }

    private static String[] DIRC = {"哈哈哈哈", "呵呵呵", "嘻嘻嘻"};
    private MyDecoder myDecoder = new MyDecoderImpl();
    private MyEncoder myEncoder = new MyEncoderImpl();
    private Section section = null;
    private String nextQuote() {
        int quote = ThreadLocalRandom.current().nextInt(DIRC.length);
        return DIRC[quote];
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        super.channelActive(ctx);
        if(ctx.channel() != null && ctx.channel().remoteAddress() != null)
            System.out.println("channelRegistered:" + ctx.channel().remoteAddress().toString());
        if(ctx.channel() != null && ctx.channel().localAddress() != null)
            System.out.println("channelRegistered:" + ctx.channel().localAddress().toString());
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        System.out.println("channelUnregistered");
    }

    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        FimRequest request = myDecoder.decoding(packet.content());
        if(section == null) {
            section = new DefaultSection();
        }
        ResultResp resultResp = section.front(request);
        if(resultResp != null && !resultResp.chenggong()) {
            ByteBuf byteBuf = getResult(request, resultResp);
            ctx.writeAndFlush(new DatagramPacket(byteBuf, packet.sender()));
            return;
        }
        ServerHandler handler = ServiceContext.getHandler(request.getType() + "");
        ResultResp handler1 = handler.handler(request);

        if(!handler1.chenggong()) {
            resultResp = section.error(request, handler1);
            ByteBuf byteBuf = getResult(request, resultResp);
            ctx.writeAndFlush(new DatagramPacket(byteBuf, packet.sender()));
            return;
        } else {
            resultResp = section.after(request);
            if(resultResp != null && !resultResp.chenggong()) {
                ByteBuf byteBuf = getResult(request, resultResp);
                ctx.writeAndFlush(new DatagramPacket(byteBuf, packet.sender()));
                return;
            }
        }
        ctx.writeAndFlush(new DatagramPacket(getResult(request, handler1), packet.sender()));

        System.out.println(new String(request.getData(), "utf-8"));
        System.out.println(packet.sender().toString());
//        ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("RESULT:" + nextQuote(), CharsetUtil.UTF_8), packet.sender()));
//        ctx.close();
    }

    public ByteBuf getResult(FimRequest request, ResultResp resultResp) {
        FimRequest request1 = new FimRequest();
        request1.setId(request.getId());
        request1.setType(request.getType());
        try {
            request1.setData(JSONObject.toJSONString(resultResp).getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ByteBuf byteBuf = myEncoder.encoding(request1);
        return byteBuf;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        System.out.println("exceptionCaught");
        ctx.close();
        cause.printStackTrace();
    }

}